package cn.ratel.db;

import cn.ratel.db.ds.DataSourceProvider;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbKit {
	private static DataSourceProvider dataSourceProvider;

	private DbKit() {

	}

	public static void setDataSourceProvider(DataSourceProvider dataSourceProvider) {
		DbKit.dataSourceProvider = dataSourceProvider;
	}

	public static Connection getConnection() {
		try {
			return dataSourceProvider.getDataSource().getConnection();
		} catch (SQLException e) {
			throw new RuntimeException("get db connection error : ", e);
		}
	}

	public static void close(Object... objects) {
		for (Object object : objects) {
			try {
				if (object != null && object instanceof Connection) {
					((Connection) object).close();
				}
				if (object != null && object instanceof PreparedStatement) {
					((PreparedStatement) object).close();
				}
				if (object != null && object instanceof ResultSet) {
					((ResultSet) object).close();
				}
			} catch (SQLException e) {
				throw new RuntimeException("close db connection error : ", e);
			}
		}
	}
}
